<template>
  <div class="container">
    <el-alert
      v-if="appInfo.authContent"
      :title="appInfo.authContent"
      type="error"
      show-icon
      :closable="false"
      style="margin-bottom: 20px"
    />
    <div class="header-search flex-yc flex-xbt">
      <h2>{{ route.query.title }}</h2>
      <el-input class="input" placeholder="请输入关键字"></el-input>
    </div>
    <div class="flex-yc flex-xbt">
      <el-upload
        action=""
        :limit="1"
        ref="upload"
        :before-upload="beforeUpload"
        :http-request="onUpload"
        :on-success="onUploadSuccess"
      >
        <el-button type="primary">上传</el-button>
      </el-upload>
      <div class="flex-yc">
        <el-button type="primary" @click="isCreateingDir = true">
          新建文件夹
        </el-button>
        <el-button type="danger" @click="onDeleteDir">删除文件夹</el-button>
        <!-- <el-button type="success">上传文件夹</el-button> -->
      </div>
    </div>
    <div class="flex-yc back-refresh">
      <el-icon :class="{ not: linkAry.length < 1 }" @click="onBack">
        <ArrowLeft />
      </el-icon>
      <el-icon :class="{ not: checkList.length < 1 }" @click="goChild">
        <ArrowRight />
      </el-icon>
      <el-icon :class="{ 'refresh-animation': loading }" @click="onRefresh">
        <RefreshRight v-loading="true" />
      </el-icon>
      <ul class="breadcrumb flex-yc">
        <li
          class="flex-yc"
          :class="{ active: item.fileId && item.fileId !== thisLink.fileId }"
          v-for="item in linkAry"
          :key="item.fileId"
          @click="goDir(item)"
        >
          {{ item.fileName }}
          <i class="iconfont icon-right"></i>
        </li>
      </ul>
    </div>
    <table-comp
      :checkbox="true"
      :pagination="false"
      :column="column"
      v-model:list="dirList"
      v-model:expandRowKeys="expandRowKeys"
      v-model:checkList="checkList"
    >
      <template v-slot:fileName="{ row }">
        <div class="file-name-wrap">
          <i
            :class="`iconfont icon-${!row.type || row.type === 1 ? 'dir' : 'file'}`"
          ></i>
          <el-popover placement="right" :width="30" trigger="hover">
            <template #reference>
              <span class="title" @click="onGetChildData(row)">
                {{ row.titleEn || row.fileName }}
              </span>
            </template>
            <div
              class="handler-btn flex-yc"
              @click="onHandlerFile(row, 'down')"
            >
              <el-icon class="el-icon--left">
                <Download />
              </el-icon>
              下载
            </div>
            <div class="handler-btn flex-yc" @click="onHandlerFile(row, 'del')">
              <el-icon class="el-icon--left">
                <Delete />
              </el-icon>
              删除
            </div>
          </el-popover>
        </div>
      </template>
    </table-comp>

    <div style="margin-top: 100px">
      <package-govern :appId="appId"></package-govern>
    </div>

    <dialog-comp
      v-model="isCreateingDir"
      title="添加文件夹"
      @onSubmit="onCreateDirSubmit"
    >
      <el-input
        placeholder="请输入文件夹名称"
        v-model="createDirName"
      ></el-input>
    </dialog-comp>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ArrowRight } from '@element-plus/icons-vue'
import dialogComp from '@/components/dialog/index.vue'
import PackageGovern from './components/PackageGovern.vue'
import {
  reqCreateChildDir,
  reqDeleteDirByFileId,
  reqDeleteFile,
  reqGetAppAllDirList,
  reqGetFilesOrDirsByFileId,
  reqUploadFileByFileId,
} from '../../api/application'
import {
  reqGetChildFilesParams,
  respAppDetailData,
  respAppDirData,
} from '../../api/types/application'
import { tableColumn } from '@/components/table/column'
import tableComp from '@/components/table/index.vue'
import {
  getUploadHttpUrl,
  MsgConfirmAsync,
  MsgError,
  MsgSuccess,
} from '@/utils/utils'
import { download } from '@/api/common'
import { UploadInstance, UploadRequestOptions } from 'element-plus'
import { useRoute } from 'vue-router'
const route = useRoute()

onMounted(() => {
  getAppAllDirList()
})

// 定义表格头部信息
const column = reactive<tableColumn[]>([
  {
    type: 'slot',
    label: '文件名',
    slotName: 'fileName',
    prop: 'titleEn',
  },
  {
    label: '大小',
    prop: 'size',
  },
  {
    label: '修改时间',
    prop: 'createTime',
  },
])

//选中的列数据
const checkList = ref<respAppDirData[]>([])
const expandRowKeys = ref<string[]>(['1', '3'])

const appId = Number(route.query.appId)

const appInfo = ref<respAppDetailData>({})
const cacheAppInfo = JSON.parse(localStorage.getItem('appInfo'))
if (cacheAppInfo !== null && appId == cacheAppInfo.id) appInfo.value = cacheAppInfo

// 表格数据
const dirList = ref<respAppDirData[]>([])
const getAppAllDirList = async () => {
  let resp = await reqGetAppAllDirList(appId)
  dirList.value = resp.data
}
// 当前所在文件夹信息
const thisLink = computed(() => linkAry.value[linkAry.value.length - 1])

// 点击添加文件夹
const isCreateingDir = ref(false)
const createDirName = ref('')
const onCreateDirSubmit = async () => {
  if (linkAry.value.length < 1) MsgError('根目录不允许添加文件夹')
  const thisDir = thisLink.value
  const reqData = { fileId: thisDir.fileId, path: '/' + createDirName.value }
  let resp = await reqCreateChildDir(reqData)
  resp.code === 0 && onRefresh()
  resp.code !== 0 && MsgError(resp.msg || '创建失败')
  isCreateingDir.value = false
  createDirName.value = ''
}

// 删除文件夹
const onDeleteDir = () => {
  console.log(checkList.value)
  if (checkList.value.length < 1) return MsgError('请至少选择一项')
  checkList.value.forEach(async (item) => {
    deleteFileOrDir(item)
  })
}
// 上传文件
const beforeUpload = async () => {
  if (linkAry.value.length < 1) {
    MsgError('根目录不允许上传文件')
    return false
  }
}

// 上传文件
const onUpload = async (options: UploadRequestOptions) => {
  const thisDir = thisLink.value
  const reqData = { fileId: thisDir.fileId, file: options.file }
  let resp = await reqUploadFileByFileId(reqData)
  if (resp.code !== 0) return MsgError(resp.msg || `文件夹上传失败`)
  else {
    onRefresh()
    onUploadSuccess()
  }
}

// 清空上传缓存
const upload = ref<UploadInstance>()
const onUploadSuccess = () => {
  upload.value!.clearFiles() //上传成功之后清除历史记录**加粗样式**
}

const linkAry = ref<reqGetChildFilesParams[]>([])
// 点击文件
const onGetChildData = async (row: respAppDirData) => {
  let resp = await reqGetFilesOrDirsByFileId({ fileId: row.id || row.fileId! })
  dirList.value = resp.data
  linkAry.value.push({
    fileId: row.id || row.fileId!,
    fileName: row.titleEn || row.fileName,
  })
}

// 后退
const onBack = async () => {
  if (linkAry.value.length <= 1) {
    getAppAllDirList()
    linkAry.value = []
  } else {
    const backData = linkAry.value[linkAry.value.length - 2]
    let resp = await reqGetFilesOrDirsByFileId({ fileId: backData.fileId })
    dirList.value = resp.data
  }
  linkAry.value.pop()
}
//前进
const goChild = () => {
  if (checkList.value.length < 1) return
  onGetChildData(checkList.value[0])
}

//到指定文件夹
const goDir = async (row: respAppDirData) => {
  if (row.fileId === thisLink.value.fileId) return false
  let resp = await reqGetFilesOrDirsByFileId({ fileId: row.id || row.fileId! })
  dirList.value = resp.data
  let index = linkAry.value.findIndex((item) => item.fileId === row.fileId)
  linkAry.value = linkAry.value.splice(0, index + 1)
  console.log(linkAry.value)
}

//刷新
const loading = ref(false)
const onRefresh = async () => {
  loading.value = true
  if (linkAry.value.length == 0) {
    await getAppAllDirList()
    loading.value = false
  } else {
    let resp = await reqGetFilesOrDirsByFileId({
      fileId: thisLink.value.fileId,
    })
    dirList.value = resp.data
    loading.value = false
  }
}
// 删除或者下载文件
const onHandlerFile = async (row: respAppDirData, type: string) => {
  if (type === 'down') {
    if (!row.downLoadUrl) return MsgError('文件不存在')
    const url = getUploadHttpUrl(row.downLoadUrl)
    download(url, row.fileName)
  } else if (type === 'del') {
    deleteFileOrDir(row)
  }
}

// 删除文件或文件夹
const deleteFileOrDir = async (row: respAppDirData) => {
  let resp
  let confirm
  if (row.id || row.fileId) {
    confirm = await MsgConfirmAsync(
      `你确定删除${row.titleEn || row.fileName}文件夹吗？删除后将删除文件夹内所有内容。`,
    )
    if (confirm) resp = await reqDeleteDirByFileId(row.id || row.fileId!)
  } else {
    confirm = await MsgConfirmAsync('你确定删除此文件吗？')
    if (confirm) {
      const parendData = thisLink.value
      resp = await reqDeleteFile({
        fileId: parendData.fileId,
        fileName: row.fileName,
      })
    }
  }
  if (confirm && resp!.code === 0) {
    MsgSuccess(resp!.msg || '刪除成功')
    onRefresh()
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 24px 27px;
  background-color: #fff;
  border-radius: 4px;

  .flex-xbt {
    margin-bottom: 22px;
  }

  .header-search {
    h2 {
      font-size: 20px;
      font-weight: bold;
      color: #021429;
    }

    .input {
      width: 260px;
    }
  }

  .back-refresh {
    height: 40px;
    padding: 0 10px;
    font-size: 16px;
    color: #000;
    border: 1px solid #ebeef5;

    :deep(.el-icon) {
      margin-right: 10px;
      font-size: 18px;
      cursor: pointer;

      &.not {
        color: #bcbcbc;
      }
    }

    .breadcrumb {
      padding-left: 10px;
      border-left: 1px solid #999;

      li {
        font-size: 16px;
        color: #bcbcbc;

        &.active {
          color: #000;
          cursor: pointer;
        }

        .iconfont {
          margin: 0 5px;
          font-size: 12px;
        }

        &:last-child {
          i {
            display: none;
          }
        }
      }
    }
  }

  .file-name-wrap {
    display: inline-block;

    .input {
      display: inline-block;
      width: 150px;
    }

    &:hover {
      span {
        color: $primary;
        text-decoration: underline;
        cursor: pointer;
      }
    }
  }

  .iconfont {
    margin-right: 5px;

    &.icon-dir {
      font-size: 14px;
      color: #ffd741;
    }
  }

  .title {
    font-size: 16px;
    color: #040724;
  }
}

.handler-btn {
  padding: 5px 0;
  font-size: 14px;
  cursor: pointer;

  &:hover {
    background-color: #f5f7fa;
  }
}

.refresh-animation {
  animation: rotate-animation 1s infinite linear;
}

@keyframes rotate-animation {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

:deep(.el-upload-list) {
  display: none;
  margin: 0;
}
</style>
